package com.yonyou.iuap.jxzy.servlet;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.iweb.exception.BusinessException;

public class AutoReadSokect2 {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private DeviceInfo deviceinfo;

	private BaedDeviceService service;

	private int port = 53000;

	private ServerSocket serverSocket;

	public AutoReadSokect2(DeviceInfo deviceinfo) throws IOException,
			ClassNotFoundException {
		this.deviceinfo = deviceinfo;
		Class<?> cls = Class.forName(deviceinfo.getExtendClass());
		service = (BaedDeviceService) ApplicationContextHolder
				.getBeanByClass(cls);
//		serverSocket = new ServerSocket(port, 3); // 连接请求队列的长度为3
		serverSocket = new ServerSocket(Integer.parseInt(deviceinfo.getDeviceCode())+42000, 3); // 连接请求队列的长度为3
		System.out.println("服务器启动监听端口"+(Integer.parseInt(deviceinfo.getDeviceCode())+42000));
	}

	public DeviceInfo getDeviceinfo() {
		return deviceinfo;
	}

	public void setDeviceinfo(DeviceInfo deviceinfo) {
		this.deviceinfo = deviceinfo;
	}

	/**
	 * 
	 */
	public void AutoRead() {
		while (serverSocket != null && !serverSocket.isClosed()) {
			Socket socket = null;
			try {
				socket = serverSocket.accept(); // 从连接请求队列中取出一个连接
				DataInputStream input = new DataInputStream(
						socket.getInputStream());
				String clientInputStr = input.readUTF();
				JSONObject jsonObject = JSONObject.parseObject(clientInputStr);
				String cardid = jsonObject.get("cardno") != null ? jsonObject
						.get("cardno").toString() : "";
				Object deviceCode = jsonObject.get("deviceCode");
				Object deviceName = jsonObject.get("deviceName");
				String deviceCode2 = getDeviceinfo().getDeviceCode();
				if (deviceCode2.equals(deviceCode)) {
					System.out.println("网口读卡器卡id：" + cardid);
					if (cardid != null && !cardid.equals("0")
							&& cardid.length() > 1) {
						deviceinfo.setUserData(cardid);
						service.processor(deviceinfo);
						deviceinfo.setUserData(null);// 清空上下文信息
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
			} finally {
				try {
					if (socket != null)
						socket.close();
					logger.error(getDeviceinfo().getDeviceCode()+"设备关闭");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private class ServerHandler implements Runnable {
		private Socket socket;

		public ServerHandler(Socket socket) {
			this.setSocket(socket);
		}

		@Override
		public void run() {
			try {
				DataInputStream input = new DataInputStream(
						socket.getInputStream());
				String clientInputStr = input.readUTF();
				JSONObject jsonObject = JSONObject.parseObject(clientInputStr);
				String cardid = jsonObject.get("cardno") != null ? jsonObject
						.get("cardno").toString() : "";
				Object deviceCode = jsonObject.get("deviceCode");
				Object deviceName = jsonObject.get("deviceName");
				String deviceCode2 = getDeviceinfo().getDeviceCode();
				if (deviceCode2.equals(deviceCode)) {
					System.out.println("网口读卡器卡id：" + cardid);
					if (cardid != null && !cardid.equals("0")
							&& cardid.length() > 1) {
						deviceinfo.setUserData(cardid);
						service.processor(deviceinfo);
						deviceinfo.setUserData(null);// 清空上下文信息
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					getSocket().close();
					// sockettole.close();
				} catch (IOException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
			}
		}

		public Socket getSocket() {
			return socket;
		}

		public void setSocket(Socket socket) {
			this.socket = socket;
		}

	}

	// 线程池
	private static ExecutorService threadPool;

	/**
	 * 单例线程池
	 * 
	 * @return
	 */
	private ExecutorService getThreadPool() {
		if (threadPool == null)
			threadPool = Executors.newCachedThreadPool();
		return threadPool;
	}

}
